import SwiftUI

struct SwitchToDarkmode: View {
    @State private var isDarkMode = false
    
    var body: some View {
        Button(action: {
            isDarkMode.toggle() // 每点一次按钮，就切换一次 isDarkMode 的值
            changeDisplayMode(state: isDarkMode)
        }, label: {
            Text("Click me.")
        })
    }
    
    func changeDisplayMode(state: Bool) {
        // 找到程序的主窗口
        let window = (UIApplication.shared.connectedScenes.first as? 
         UIWindowScene)?.windows.first!
        
        // 修改主窗口的样式
        window!.overrideUserInterfaceStyle = isDarkMode ? .dark : .light
        
        // 让修改生效
        UserDefaults.standard.set(isDarkMode, forKey: "DARK_MODE")
    }
}
